/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.I18nUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.publish.entity.EleSourceGroupPublish;
import com.thinkgem.jeesite.modules.publish.entity.EleTempletPublish;
import com.thinkgem.jeesite.modules.publish.service.EleSourceGroupPublishService;
import com.thinkgem.jeesite.modules.publish.service.EleTempletPublishService;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.FormAuthenticationFilter;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.SwitchUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * 用户Controller
 * 
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private OfficeService officeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private EleEquipmentService eleEquipmentService;
	@Autowired
	private EleTempletPublishService eleTempletPublishService;
	@Autowired
	private EleSourceGroupService eleSourceGroupService;
//	@Autowired
//	private DemoService demoService;
	
	
	@ModelAttribute
	public User get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return systemService.getUser(id);
		} else {
			return new User();
		}
	}

	@RequestMapping("welcome")
	public String welcome(HttpServletRequest request,Model model) {
		//System.out.println(demoService.sayHello("Welcome"));
		User user = UserUtils.getUser();
		// 获取区域管理员
		User checkUser = user.getAreaBy();
		// 获取维保用户
		User operate = user.getMaintainBy();

		User admin = UserUtils.getAdminUser();
		model.addAttribute("user", user);
		model.addAttribute("operate", operate);
		model.addAttribute("checkUser", checkUser);
		model.addAttribute("admin", admin);
		
		//下属用户
		List<User> branches = systemService.getBranchForUserWithoutSelf(user);
		model.addAttribute("branches", branches.size());

		//下属设备
		List<User> branches1 = systemService.getBranchForUserWithSelf(user);
		model.addAttribute("equipments", systemService.findControlEqipmentForUserByBranches(branches1).size());
		model.addAttribute("equipments_all", systemService.findControlEqipmentForUserByBranchesAll(branches1).size());
		
		
		//用户申请记录
		User thisUser = UserUtils.getUser();
		User condUser = new User();
		condUser.setDelFlag(User.DEL_FLAG_AUDIT);
		//condUser.setCreateBy(thisUser);
		List<User> branchesForthisUser = this.getSubListForUserForCheck(thisUser);

		List<User> userApplys = systemService.findUserForCheck(branchesForthisUser, condUser.getDelFlag());
		System.out.println("------------------------<<<<<<");
		model.addAttribute("userApplys", userApplys.size());

      	// 设备申请记录
		EleEquipment condDevice = new EleEquipment();
		//condDevice.setCreateBy(thisUser);
		//condDevice.setCreateBy(new User(UserUtils.getUser().getId()));
		condDevice.setDelFlag(User.DEL_FLAG_AUDIT);

		List<EleEquipment> deviceApplys = eleEquipmentService.findPageForCheck(branchesForthisUser, condDevice.getDelFlag());
		model.addAttribute("deviceApplys", deviceApplys.size());

		//模板申请
		EleTempletPublish condtemplate = new EleTempletPublish();
		//condtemplate.setCreateBy(thisUser);
		condtemplate.setDelFlag(User.DEL_FLAG_AUDIT);

	    List<EleTempletPublish> templateApplys = eleTempletPublishService.findPublishPageForCheck(branchesForthisUser, condtemplate.getDelFlag());
		model.addAttribute("templateApplys", templateApplys.size());
			
		//节目申请
		EleSourceGroup condGroup = new EleSourceGroup();
		//condGroup.setCreateBy(thisUser);
		condGroup.setDelFlag(User.DEL_FLAG_AUDIT);

		List<EleSourceGroup> groupApplys = eleSourceGroupService.findPageForCheckForProgram(branches, condGroup.getDelFlag());
		System.out.println("------------------------<<<<<<");

		model.addAttribute("groupApplys", groupApplys.size());
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		model.addAttribute("language", locale.getLanguage());
		if(locale.getLanguage().equals("zh")) {
			model.addAttribute("chinese", "chinese");
		}
		return "modules/sys/welcome";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "index" })
	public String index(User user, Model model) {
		return "modules/sys/userIndex";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "list", "" })
	public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		String remark = "users";
		model.addAttribute("allRoles", systemService.findAllRoleForUsers(remark));
		System.out.println(user.getRoleList());
		System.out.println(user.getSqlMap());
		user.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "", ""));
		user.setDelFlag(null);
		List<User> list = systemService.findList(user);
		for (User temuser : list) {
			String locale = I18nUtils.getLocaleStr();
			String label = Global.US.equals(locale)? "Normal" : "正常";
			if(User.DEL_FLAG_EXPIRED.equals(temuser.getDelFlag())){
				label = Global.US.equals(locale)? "Expired" : "过期";
			}else if(!User.DEL_FLAG_NORMAL.equals(temuser.getDelFlag())){
				label = Global.US.equals(locale)? "In approval" : "审批中";
			}
			temuser.setRemarks(label);
		}	
		Set<String> ids = new HashSet<String>();
		for(User temuser:list){
			 String officeId = temuser.getOffice().getId();
			 String companyId = temuser.getCompany().getId();
			ids.add(officeId);
			ids.add(companyId);
		}
		List<Office> listOffice = officeService.findList(true);
		Set<String> resultSet = new HashSet<String>();
		for (String oid : ids) {
			resultSet.add(oid);
			Office tmp = officeService.get(oid);
			for (int i = 0; i < listOffice.size(); i++) {
				Office item = listOffice.get(i);
				if (item.getId().equals(tmp.getParentId())) {
					System.out.println(item);
					tmp = item;
					i = -1;
					resultSet.add(item.getId());
				}
			}
		}
		List<User> managers = new ArrayList<User>();
		for(User tmp:list){
			if(!tmp.getUserType().equals("4") && !tmp.getUserType().equals("1")){
				managers.add(tmp);
			}
		}
		List<User> approval = new ArrayList<User>();
		for(User tmp:list){
			if(User.DEL_FLAG_AUDIT.equals(tmp.getDelFlag())){
				approval.add(tmp);
			}
		}
		list.remove(UserUtils.getUser());
		list.removeAll(managers);
		list.removeAll(approval);
		managers.remove(UserUtils.getUser());
		for(User tmp:list){
			tmp.setEmail(tmp.getId());
		}
		System.out.println("managers : "+managers.size());
		User temUser = null;
		for (String oid : resultSet) {
			System.out.println(oid);
			Office item = officeService.get(oid);
			temUser = new User();
			temUser.setId(item.getId());
			temUser.setOffice(new Office(item.getParentId(), item.getName()));
			temUser.setPhoto(item.getName());
			temUser.setLoginFlag("display:none;");

			for(User tmp:managers){
				if(tmp.getOffice().getId().equals(oid)){
					System.out.println(tmp.getName());
					temUser.setName(tmp.getName());
					temUser.setMobile(tmp.getMobile());
					temUser.setRole(tmp.getRole());
					temUser.setRemarks(tmp.getRemarks());
					temUser.setLoginFlag("display:visible;");
					temUser.setEmail(tmp.getId());
					break;
				}
			}
			list.add(temUser);
		}
		System.out.println(list.size());
		model.addAttribute("list", list);
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		model.addAttribute("language", locale.getLanguage());
		if(locale.getLanguage().equals("zh")) {
			model.addAttribute("chinese", "chinese");
		}
		return "modules/sys/userList";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "sublist", "" })
	public String sublist(HttpServletRequest request, HttpServletResponse response, Model model) {
	
		String userId = request.getParameter("userId");
		User current = systemService.getUser(userId);
		List<User> resultList = getSubListForUser(current);
		Set<String> ids = new HashSet<String>();
		for(User temuser:resultList){
			 String officeId = temuser.getOffice().getId();
			 String companyId = temuser.getCompany().getId();
			ids.add(officeId);
			ids.add(companyId);
		}
		List<Office> listOffice = officeService.findList(true);
		Set<String> resultSet = new HashSet<String>();
		for (String oid : ids) {
			resultSet.add(oid);
			Office tmp = officeService.get(oid);
			for (int i = 0; i < listOffice.size(); i++) {
				Office item = listOffice.get(i);
				if (item.getId().equals(tmp.getParentId())) {
					System.out.println(item);
					tmp = item;
					i = -1;
					resultSet.add(item.getId());
				}
			}
		}
		List<User> managers = new ArrayList<User>();
		for(User tmp:resultList){
			if(!tmp.getUserType().equals("4") && !tmp.getUserType().equals("1")){
				managers.add(tmp);
				System.out.println(tmp.getName());
			}
		}
		resultList.remove(UserUtils.getUser());
		resultList.removeAll(managers);
		managers.remove(UserUtils.getUser());

		for(User tmp:resultList){
			tmp.setEmail(tmp.getId());
		}
		User temUser = null;
		for (String oid : resultSet) {
			Office item = officeService.get(oid);
			temUser = new User();
			temUser.setId(item.getId());
			temUser.setOffice(new Office(item.getParentId(), item.getName()));
			temUser.setPhoto(item.getName());
			temUser.setLoginFlag("display:none;");

			for(User tmp:managers){
				if(tmp.getOffice().getId().equals(oid)){
					System.out.println(tmp.getName());
					temUser.setName(tmp.getName());
					temUser.setMobile(tmp.getMobile());
					temUser.setRole(tmp.getRole());
					temUser.setRemarks(tmp.getRemarks());
					temUser.setLoginFlag("display:visible;");
					temUser.setEmail(tmp.getId());

					break;
				}
			}
			resultList.add(temUser);
		}

		model.addAttribute("list", resultList);
		return "modules/sys/userList";
	}
	
	

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "controlerlist", "" })
	public String controlerlist(HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = new User();
		List<User> list = systemService.findList(user);
		String eqId = request.getParameter("eqId");
		EleEquipment eq = eleEquipmentService.get(eqId);
		String companyId = eq.getCompany().getId();
		String officeId = eq.getOffice().getId();
		User current = UserUtils.getUser();

		
		List<User> resultList = systemService.findUsersByCompanyAndOffice(companyId, officeId);
		resultList.addAll(systemService.findUsersByCompanyAndOffice(companyId,companyId));
		if(current.isAdmin()){
			resultList.add(current);
		}else{
			resultList.add(UserUtils.getAdminUser());
		}
		Set<String> ids = new HashSet<String>();
		for(User temuser:resultList){
			 String oiceId = temuser.getOffice().getId();
			 String canyId = temuser.getCompany().getId();
			ids.add(oiceId);
			ids.add(canyId);
		}
		List<Office> listOffice = officeService.findList(true);
		Set<String> resultSet = new HashSet<String>();
		for (String oid : ids) {
			resultSet.add(oid);
			Office tmp = officeService.get(oid);
			for (int i = 0; i < listOffice.size(); i++) {
				Office item = listOffice.get(i);
				if (item.getId().equals(tmp.getParentId())) {
					System.out.println(item);
					tmp = item;
					i = -1;
					resultSet.add(item.getId());
				}
			}
		}
		List<User> managers = new ArrayList<User>();
		for(User tmp:resultList){
			if(!tmp.getUserType().equals("4")){
				managers.add(tmp);
				System.out.println(tmp.getName());
			}
		}
		resultList.remove(UserUtils.getUser());
		resultList.removeAll(managers);

		
		
		User temUser = null;
		for (String oid : resultSet) {
			Office item = officeService.get(oid);
			temUser = new User();
			temUser.setId(item.getId());
			temUser.setOffice(new Office(item.getParentId(), item.getName()));
			temUser.setPhoto(item.getName());
			temUser.setLoginFlag("display:none;");
			resultList.add(temUser);
			for(User tmp:managers){
				if(tmp.getOffice().getId().equals(oid)){
					System.out.println(tmp.getName());
					temUser.setName(tmp.getName());
					temUser.setMobile(tmp.getMobile());
					temUser.setRole(tmp.getRole());
					temUser.setRemarks(tmp.getRemarks());
					temUser.setLoginFlag("display:visible;");
					temUser.setEmail(tmp.getId());

					break;
				}
			}
			}
		model.addAttribute("list", resultList);
		return "modules/sys/userList";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "controlequipmentlist", "" })
	public String controlequipmentlist(HttpServletRequest request, HttpServletResponse response, Model model) {
		List<Office> listTree = new ArrayList<>();

		String userId = request.getParameter("userId");
		User current = systemService.getUser(userId);
		String parentId = current.getCompany().getId();
		String parentIdsStr = current.getCompany().getParentIds();
		Office office = new Office();
		List<Office> officeList = officeService.findList(office);
		for (Office item : officeList) {
			if ((parentIdsStr.contains(item.getId() + ",") && !parentIdsStr.equals(item.getParentIds()))
					|| (item.getParentIds().contains(parentIdsStr) && !parentIdsStr.equals(item.getParentIds()))
					|| parentId.equals(item.getId())) {
				item.setAddress(null);
				item.setEmail(null);
				item.setFax(null);
				item.setRemarks(null);
				item.setPhone("display:none;");
				listTree.add(item);
			}
		}
		
		
		User user = new User();
		List<User> list = systemService.findList(user);
		Role role = current.getRole();
		List<User> resultList = new ArrayList<User>();
		if (current.getUserType().equals("1")) {
			resultList = list;
		} else if (current.getUserType().equals("4")) {
			resultList.add(current);
		} else if (current.getUserType().equals("3")) {
			for (User usr : list) {
				if (usr.getUserType().equals("4")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
				}
			}
			resultList.add(current);
		} else {
			Set<String> offices = new HashSet<String>();
			for (User usr : list) {
				if (usr.getUserType().equals("3")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
					offices.add(usr.getOffice().getId());
				}
			}
			offices.add(current.getOffice().getId());
			for (User usr : list) {
				if (usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())) {
					resultList.add(usr);
				}
			}
			resultList.add(current);
		}
		
		Set<String> eqIds = new HashSet<>();
		for(User tmp:resultList){
			EleEquipment eleEquipment = new EleEquipment();
			eleEquipment.setCompany(tmp.getCompany());
			eleEquipment.setOffice(tmp.getOffice());

			List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipment);
			for (EleEquipment equipment : listEquipment) {
				if(eqIds.contains(equipment.getId())){
					continue;
				}
				eqIds.add(equipment.getId());
				Office Office = new Office();
				Office.setId(equipment.getId());
				Office.setParent(new Office(equipment.getOffice().getId()));
				Office.setAddress(equipment.getCode());
				Office.setZipCode(equipment.getName());
				Office.setEmail(equipment.getType().getName());
				Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
				Office.setRemarks(equipment.getRemarks());
				Office.setPhone("");
				listTree.add(Office);
			}
		}
		model.addAttribute("eleEquipment", new EleEquipment());

		model.addAttribute("list", listTree);
		return "modules/equipment/eleEquipmentList";
	}
	public List<EleEquipment> getUnderControllEquipmentList(User current){
		List<EleEquipment> listTree = new ArrayList<>();
		User user = new User();
		List<User> list = systemService.findList(user);
		Role role = current.getRole();
		List<User> resultList = new ArrayList<User>();
		if (current.getUserType().equals("1")) {
			resultList = list;
		} else if (current.getUserType().equals("4")) {
			resultList.add(current);
		} else if (current.getUserType().equals("3")) {
			for (User usr : list) {
				if (usr.getUserType().equals("4")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
				}
			}
			resultList.add(current);
		} else {
			Set<String> offices = new HashSet<String>();
			for (User usr : list) {
				if (usr.getUserType().equals("3")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
					offices.add(usr.getOffice().getId());
				}
			}
			offices.add(current.getOffice().getId());
			for (User usr : list) {
				if (usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())) {
					resultList.add(usr);
				}
			}
			resultList.add(current);
		}
		
		Set<String> eqIds = new HashSet<>();
		for(User tmp:resultList){
			EleEquipment eleEquipment = new EleEquipment();
			eleEquipment.setCompany(tmp.getCompany());
			eleEquipment.setOffice(tmp.getOffice());

			List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipment);
			for (EleEquipment equipment : listEquipment) {
				if(eqIds.contains(equipment.getId())){
					continue;
				}	
				listTree.add(equipment);
			}
		}
		return listTree;
	}
	/**
	 * 我的申请
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping("applylist")
	public String applylist(User user, String isFirst, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		User thisUser = UserUtils.getUser();
		user.setCreateBy(thisUser);
		if(StringUtils.isEmpty(isFirst)){
			user.setDelFlag(User.DEL_FLAG_AUDIT);
		}
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
		model.addAttribute("page", page);
		model.addAttribute("isFirst", "no");

		return "modules/sys/myUserList";
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping("resubmit")
	@ResponseBody
	public Result resubmitUser(String userList, HttpServletRequest request, HttpServletResponse response, Model model) {
		String users = userList.substring(0, userList.length() - 1);
		String status = EleSourceGroup.DEL_FLAG_AUDIT;
		String msg = "已重新提交审核";
		System.out.println(users);
		User thisuser = UserUtils.getUser();
		systemService.batchUpdateUserStatus(users, status, thisuser.getId(), "");
		return new Result(Result.SUCCESS, msg, null);
	}

	/**
	 * 审核记录
	 * @param user
	 * @param flag
	 * @param isFirst
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:user:check")
	@RequestMapping("mychecklist")
	public String checklist(User user, boolean flag,String isFirst, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		System.out.println(isFirst);
		if(StringUtils.isEmpty(isFirst)){
			user.setDelFlag(User.DEL_FLAG_AUDIT);
		}
		User thisUser = UserUtils.getUser();
		List<User> branches = this.getSubListForUserForCheck(thisUser);
		Page<User> page = new Page<>();
		if(!branches.isEmpty()){
			page = systemService.findUserForCheck(user, new Page<User>(request, response), branches,user.getDelFlag());
		}
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
		//user.setCheckBy(thisUser);
		model.addAttribute("page", page);
		model.addAttribute("flag", flag);
		model.addAttribute("isFirst", "no");
		model.addAttribute("language", locale.getLanguage());
		return "modules/sys/myUserCheckList";
	}

	@RequiresPermissions("sys:user:check")
	@RequestMapping("checkUser")
	@ResponseBody
	public Result checkUser(String userList, String flag, String comment) {
		String users = userList.substring(0, userList.length() - 1);
		System.out.println(users);
		String status;
		String msg;

		User thisuser = UserUtils.getUser();
		if ("reject".equals(flag)) {
			status = EleSourceGroup.DEL_FLAG_AUDIT_NO;
			String locale = I18nUtils.getLocaleStr();
			msg = "未通过审核";
			if(Global.US.equals(locale)){
				msg = "Not passed";
			}
		}else{
			status = EleSourceGroup.DEL_FLAG_NORMAL;
			String locale = I18nUtils.getLocaleStr();
			msg = "审核通过";
			if(Global.US.equals(locale)){
				msg = "passed";
			}
		}
		systemService.batchUpdateUserStatus(users, status, thisuser.getId(), comment);
		return new Result(Result.SUCCESS, msg, null);
	}

	@RequestMapping("batchdelete")
	@ResponseBody
	public Result batchDelete(String userList, String type) {
		String users = userList.substring(0, userList.length() - 1);
		System.out.println(users);

		String status = EleSourceGroup.DEL_FLAG_DELETE;
		if("approval".equals(type)){
			systemService.delApprovalUserStatus(users, status);
		}
		else{
			systemService.delApplyUserStatus(users, status);
		}
		String[] userIds = userList.split(",");
		for(String userId:userIds){
			User tmp = systemService.getUser(userId.replace("'",""));
			deleteUser(tmp);
		}
		return new Result(Result.SUCCESS, "删除成功", null);

	}
	@ResponseBody
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "listData" })
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response) {
		Page<User> list = systemService.findUser(new Page<User>(request, response), user);
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		list.setLocale(locale);
		return list;
	}

	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(User user,HttpServletRequest request, Model model) {
		// 清除之前处理用户的缓存
		UserUtils.removeCache(UserUtils.getUser().getId() + "_CREATE_USER");

		if (user.getCompany() == null || user.getCompany().getId() == null) {
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice() == null || user.getOffice().getId() == null) {
			user.setOffice(UserUtils.getUser().getOffice());
		}
		model.addAttribute("user", user);
		String remark = "users";
		//System.out.println(systemService.findAllRoleForUsers(remark));
		System.out.println(systemService.findAllRoleForUsers(remark).size());
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  

		model.addAttribute("allRoles", systemService.findAllRoleForUsers(remark));
		if(locale.getLanguage().equals("zh")) {
			model.addAttribute("language", locale.getLanguage()+"-cn");

		}else {
			model.addAttribute("language", locale.getLanguage());

		}
		System.out.println( locale.getLanguage());
		return "modules/sys/userForm";
	}
	
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "edit")
	public String edit(User user, Model model,HttpServletRequest request) {
		// 清除之前处理用户的缓存
		UserUtils.removeCache(UserUtils.getUser().getId() + "_CREATE_USER");

		if (user.getCompany() == null || user.getCompany().getId() == null) {
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice() == null || user.getOffice().getId() == null) {
			user.setOffice(UserUtils.getUser().getOffice());
		}
		model.addAttribute("user", user);
		String remark = "users";
		//System.out.println(systemService.findAllRoleForUsers(remark));
		model.addAttribute("allRoles", systemService.findAllRoleForUsers(remark));
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
		if(locale.getLanguage().equals("zh")) {
			model.addAttribute("language", locale.getLanguage()+"-cn");
		}else {
			model.addAttribute("language", locale.getLanguage());
		}
		return "modules/sys/userEdit";
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model,RedirectAttributes redirectAttributes) {
		System.out.println(user.getRole().getId());
		user.setUserType(user.getRole().getId());
		boolean isExists = false;
		if(StringUtils.isEmpty(user.getId())){
			List<User> tmp = systemService.getUserByMobile(user.getMobile());
			if(tmp.isEmpty()){
				isExists = mgrUserOffice(user,request);
			}else{
				isExists = true;
			}
			
			
		}
		if(isExists){
			model.addAttribute("user", user);
			String remark = "users";
			model.addAttribute("allRoles", systemService.findAllRoleForUsers(remark));
			String locale = I18nUtils.getLocaleStr();
			String msg = "该区域当前角色已存在";
			if(Global.US.equals(locale)){
				msg = "The current role in the region has already existed";
			}
			addMessage(model, msg);
			return form(user,request, model);
		}
		if(StringUtils.isEmpty(user.getId())){
			// 字典中配置默认密码
			user.setPassword(SystemService.entryptPassword(DictUtils.getDictValue("password", "systemvalue", "123456")));
		}
		user.setLoginFlag(Global.YES);
		if (!beanValidator(model, user)) {
			return form(user,request, model);
		}
		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "保存用户'" + user.getLoginName() + "'失败，帐号已存在";
			if(Global.US.equals(locale)){
				msg = "save user'" + user.getLoginName() + "'fail，account has already existed";
			}
			addMessage(model, msg);
			/*return "redirect:"+Global.getAdminPath()+"/source/floor/eleSourceFloored/?repage";
			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，帐号已存在");*/
			return form(user,request, model);
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		Role role = user.getRole();
		for (Role r : systemService.findAllRole()) {
			if ((role.getId()).equals(r.getId())) {
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		
		//设置维保人员和区域管理员
		if(user.getUserType().equals("4")){
			User maintainer = systemService.getMaintainerForUser(user.getCompany().getId(), user.getOffice().getId(), "3");
			user.setMaintainBy(maintainer);
			User areaer = systemService.getMaintainerForUser(user.getCompany().getId(), user.getCompany().getId(), "2");
			user.setAreaBy(areaer);
			if(maintainer == null || areaer == null) {
				model.addAttribute("user", user);
				String remark = "users";
				model.addAttribute("allRoles", systemService.findAllRoleForUsers(remark));
				String locale = I18nUtils.getLocaleStr();
				String msg = "此区域缺少有效的管理人员";
				if(Global.US.equals(locale)){
					msg = "There is a lack of managers in this area";
				}
				addMessage(redirectAttributes, msg);
				return "redirect:"+Global.getAdminPath()+"/sys/user/info/?repage";
			}
		}else if(user.getUserType().equals("3")){
			User maintainer = systemService.getMaintainerForUser(user.getCompany().getId(), user.getCompany().getId(), "2");
			user.setMaintainBy(maintainer);
			User areaer = systemService.getMaintainerForUser(user.getCompany().getId(), user.getCompany().getId(), "2");
			user.setAreaBy(areaer);
			if(maintainer == null || areaer == null) {
				model.addAttribute("user", user);
				String remark = "users";
				model.addAttribute("allRoles", systemService.findAllRoleForUsers(remark));
				String locale = I18nUtils.getLocaleStr();
				String msg = "此区域缺少有效的管理人员";
				if(Global.US.equals(locale)){
					msg = "There is a lack of managers in this area";
				}
				addMessage(redirectAttributes, msg);
				return "redirect:"+Global.getAdminPath()+"/sys/user/info/?id=" + user.getId();
			}
		}
		
		// 审核控制没有关闭 并且没有用户权限的时候
		if (!UserUtils.getSubject().isPermitted("sys:user:check") && !SwitchUtils.isClose("sys:user:check")) {
			user.setCheckBy(UserUtils.getCheckUser(""));
			user.setDelFlag(User.DEL_FLAG_AUDIT);
		} else {
			user.setCheckDate(new Date());
			user.setCheckBy(UserUtils.getUser());
			user.setDelFlag(User.DEL_FLAG_NORMAL);
		}
		UserUtils.putCache(UserUtils.getUser().getId() + "_CREATE_USER", user);
//		return "modules/sys/userInfoConfirm";
		// Edited By Jyz (2018.5)
		return formsave(request, model);
	}
	private boolean mgrUserOffice(User user, HttpServletRequest request) {
		boolean needCreateCompany = true;
		String companyName = request.getParameter("company.name");
		System.out.println(companyName);
		Office company = null;
		if (StringUtils.isNotEmpty(companyName)) {
			company = officeService.getOfficeByName(companyName.trim());
			if(company != null){
			if (company.getName().equals(companyName.trim())) {
				needCreateCompany = false;
			}
			}
		}
		if(needCreateCompany){
			return false;
		}
		boolean needCreateOffice = true;
		String officeName = request.getParameter("office.name");
		System.out.println(officeName);

		Office office = null;
		System.out.println(user.getUserType());
		if(!user.getUserType().equals("2")){
			
			if (StringUtils.isNotEmpty(officeName)) {
				office = officeService.getOfficeByName(officeName.trim());
				if(office != null){
				if (office.getName().equals(officeName.trim())) {
					needCreateOffice = false;
				}
				}
			}
		}else{
			needCreateOffice = false;
			office = company;
		}
		
		if(needCreateOffice){
			return false;
		}
		
		if(user.getUserType().equals("2") || user.getUserType().equals("3")){
			User cond = new User();

			cond.setCompany(company);

			cond.setOffice(office);
			cond.setUserType(user.getUserType());
			if(systemService.findUsersCountForTheArea(cond) >= 1){
				return true;
			}
			
		}
	
		return false;
	}
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "formsave")
	public String formsave(HttpServletRequest request,Model model) {
		User user = (User) UserUtils.getCache(UserUtils.getUser().getId() + "_CREATE_USER");
		// 保存用户信息
		mgrUserOffice(user);

		System.out.println(user);
		
		if(StringUtils.isEmpty(user.getOffice().getName())){
			user.setOffice(user.getCompany());
		}
		System.out.println(user);
		System.out.println(user.getId());
		if(StringUtils.isEmpty(user.getId())){
			model.addAttribute("operation", "add");
		}else{
			model.addAttribute("operation", "edit");
		}
		systemService.saveUser(user);

		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
			UserUtils.clearCache();
		}
		UserUtils.removeCache(UserUtils.getUser().getId() + "_CREATE_USER");
		model.addAttribute("user", user);
		model.addAttribute("password", DictUtils.getDictValue("password", "systemvalue", "123456"));

		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
		model.addAttribute("language", locale.getLanguage());
		return "modules/sys/userInfoConfirmTips";
	}
	
	private boolean mgrUserOffice(User user) {
		boolean needCreateCompany = true;
		String companyId = user.getCompany().getId();//request.getParameter("company.id");
		String companyName = user.getCompany().getName();//request.getParameter("company.name");
		System.out.println(companyName);
		Office company = null;
		if (StringUtils.isNotEmpty(companyName)) {
			company = officeService.getOfficeByName(companyName.trim());
			if(company != null){
			if (company.getName().equals(companyName.trim())) {
				needCreateCompany = false;
			}
			}
		}
		boolean needCreateOffice = true;
		String officeId = user.getOffice().getId();//request.getParameter("office.id");
		String officeName = user.getOffice().getName();//request.getParameter("office.name");
		System.out.println(officeName);

		Office office = null;
		System.out.println(user.getUserType());
		if(!user.getUserType().equals("2")){
			
			if (StringUtils.isNotEmpty(officeName)) {
				office = officeService.getOfficeByName(officeName.trim());
				if(office != null){
				if (office.getName().equals(officeName.trim())) {
					needCreateOffice = false;
				}
				}
			}
		}else{
			needCreateOffice = false;
			office = company;
		}
		
		
		
		if(user.getUserType().equals("2") || user.getUserType().equals("3")){
			User cond = new User();

			cond.setCompany(company);

			cond.setOffice(office);
			cond.setUserType(user.getUserType());
			if(systemService.findUsersCountForTheArea(cond) >= 1){
				return true;
			}
			
		}
		if (needCreateCompany) {
			company = new Office();
			if(!StringUtils.isEmpty(companyName)){
			company.setName(companyName);
			company.setParent(officeService.get("1"));
			company.setType("1");
			company.setUseable(Global.YES);
			company.setArea(new Area("1"));
			company.setGrade("1");
			officeService.save(company);
			}
		}	
		if (needCreateOffice) {
			if(!StringUtils.isEmpty(officeName)){
			office = new Office();
			office.setName(officeName);
			office.setParent(company);
			office.setType("2");
			office.setUseable(Global.YES);
			office.setArea(new Area("1"));
			office.setGrade("2");
			officeService.save(office);
			}else{
				office = company;
			}
		}
	
		user.setCompany(company);
		user.setOffice(office);
		if(user.getUserType().equals("2")){
			user.setOffice(company);
		}
		return false;
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "delete")
	public String delete(User user, RedirectAttributes redirectAttributes) {
		if (UserUtils.getUser().getId().equals(user.getId())) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "删除用户失败, 不允许删除当前用户";
			if(Global.US.equals(locale)){
				msg = "Delete user failure and do not allow users to delete the current user";
			}
			addMessage(redirectAttributes, msg);
		} else if (User.isAdmin(user.getId())) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "删除用户失败, 不允许删除超级管理员用户";
			if(Global.US.equals(locale)){
				msg = "Delete user failure and do not allow users to delete superadministrator users";
			}
			addMessage(redirectAttributes, msg);
		} else {
				deleteUser(user);
			String locale = I18nUtils.getLocaleStr();
			String msg = "删除用户成功";
			if(Global.US.equals(locale)){
				msg = "Delete user success";
			}
				addMessage(redirectAttributes, msg);
			
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}
	
	public void deleteUser(User user){
		if(user.getUserType().equals("2") || user.getUserType().equals("3")){
			List<User> branches = this.getSubListForUser(user);
			for(User tmp:branches){
				EleEquipment eleEquipment = new EleEquipment();
				eleEquipment.setCompany(tmp.getCompany());
				eleEquipment.setOffice(tmp.getOffice());
				List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipment);
				for (EleEquipment equipment : listEquipment) {
					eleEquipmentService.delete(equipment);
				}
				Office office = tmp.getOffice();
				officeService.delete(office);
				if (user.getUserType().equals("2")) {
					Office company = tmp.getCompany();
					officeService.delete(company);
				}
			}
			for(User tmp:branches){
				systemService.deleteUser(tmp);
			}
			Office o = user.getOffice();
			officeService.delete(o);
		}
		systemService.deleteUser(user);
	}

	/**
	 * 导出用户数据
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(User user, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
			Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
			page.setLocale(locale);
			new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 导入用户数据
	 * 
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if (Global.isDemoMode()) {
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<User> list = ei.getDataList(User.class);
			for (User user : list) {
				try {
					if ("true".equals(checkLoginName("", user.getLoginName()))) {
						user.setPassword(SystemService.entryptPassword("123456"));
						BeanValidators.validateWithException(validator, user);
						systemService.saveUser(user);
						successNum++;
					} else {
						failureMsg.append("<br/>登录名 " + user.getLoginName() + " 已存在; ");
						failureNum++;
					}
				} catch (ConstraintViolationException ex) {
					failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList) {
						failureMsg.append(message + "; ");
						failureNum++;
					}
				} catch (Exception ex) {
					failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：" + ex.getMessage());
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 下载导入用户数据模板
	 * 
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "用户数据导入模板.xlsx";
			List<User> list = Lists.newArrayList();
			list.add(UserUtils.getUser());
			new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 重置用户密码
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "resetPassword")
	public String resetPassword(User user, Model model) {
		String newPassword = DictUtils.getDictValue("password", "systemvalue", "123456");
		systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
		user.setLoginDate(null);
		systemService.updateUserLoginInfo(user);
		model.addAttribute("message", "重置密码成功");
		model.addAttribute("user", user);

		return "redirect:" + adminPath + "/sys/user/list?repage";
	}

	/**
	 * 验证登录名是否有效
	 * 
	 * @param oldLoginName
	 * @param loginName
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName != null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName != null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}
	

	/**
	 * 验证 手机号码是否重复
	 * 
	 * @param userId
	 * @param mobile
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkMobile")
	public boolean checkMobile(String userId, String mobile) {
		List<User> users = systemService.getUserByMobile(mobile);
		return null == users || users.isEmpty() || users.size() < 2 && users.get(0).getId().equals(userId);
	}

	/**
	 * 用户信息显示及保存
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "info")
	public String info(User user, Model model,HttpServletRequest request) {
		User loginUser = UserUtils.getUser();
		if (null == user || StringUtils.isEmpty(user.getId())) {
			model.addAttribute("user", loginUser);
			model.addAttribute("isSelf", true);
		} else {
			model.addAttribute("user", user);
			model.addAttribute("isSelf", loginUser.getId().equals(user.getId()));
		}
		String showType = request.getParameter("showtype");
		if("2".equals(showType)){
			model.addAttribute("show", "no");
		}else{
			model.addAttribute("show", "yes");
		}
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		model.addAttribute("language", locale.getLanguage());
		model.addAttribute("Global", new Global());
		return "modules/sys/userInfo";
	}

	/**
	 * 返回用户信息
	 * 
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "infoData")
	public User infoData() {
		return UserUtils.getUser();
	}

	/**
	 * 修改个人用户密码
	 * 
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(HttpServletRequest request, HttpServletResponse response, String oldPassword,
			String newPassword, Model model) {
		User user = UserUtils.getUser();
		boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
		String result = Result.FAILURE;
		String message = "";
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
			if (SystemService.validatePassword(oldPassword, user.getPassword())) {
				systemService.updateUserLoginInfo(user);
				systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
				message = "修改密码成功";
				model.addAttribute("message", "修改密码成功");
				result = Result.SUCCESS;
				return "redirect:" + adminPath;

			} else {
				message = "修改密码失败，旧密码错误";
				result = Result.FAILURE;
			}
		}
		model.addAttribute("message", message);
		if (mobile) {
			return renderString(response, new Result(result, message, ""));
		}
		model.addAttribute("user", user);
		return "modules/sys/userModifyPwd";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String officeId,
			HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<User> list = systemService.findUserByOfficeId(officeId);
		for (int i = 0; i < list.size(); i++) {
			User e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", "u_" + e.getId());
			map.put("pId", officeId);
			map.put("name", StringUtils.replace(e.getName(), " ", ""));
			mapList.add(map);
		}
		return mapList;
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "recheck")
	public String recheck(String userId, RedirectAttributes redirectAttributes) {
		User user = new User(userId);
		user.setDelFlag(User.DEL_FLAG_AUDIT);
		Result result = systemService.check(user);
		String locale = I18nUtils.getLocaleStr();
		String msg = "已经重新提交审核";
		if(Global.US.equals(locale)){
			msg = "The review has been re submitted";
		}
		addMessage(redirectAttributes, msg);

	/*	addMessage(redirectAttributes, "已经重新提交审核!");*/
		return "redirect:" + adminPath + "/sys/user/info?id=" + userId;
	}

	@RequiresPermissions("sys:user:check")
	@RequestMapping(value = "check")
	public String check(String userId, String delFlag, RedirectAttributes redirectAttributes) {
		User user = new User(userId);
		user.setDelFlag(delFlag);
		user.setCheckDate(new Date());
		user.setCheckBy(UserUtils.getUser());
		Result result = systemService.check(user);
		addMessage(redirectAttributes, result.getMsg());
		return "redirect:" + adminPath + "/sys/user/info?id=" + userId;
	}
	
	public List<User> getSubListForUser(User current){
		User user = new User();
		List<User> list = systemService.findList(user);
		Role role = current.getRole();
		List<User> resultList = new ArrayList<User>();
		if (current.getUserType().equals("1")) {
			for (User usr : list) {
				if (!usr.getUserType().equals("1")) {
					resultList.add(usr);
				}
			}
		} else if (current.getUserType().equals("4")) {
			//resultList.add(current);
		} else if (current.getUserType().equals("3")) {
			for (User usr : list) {
				if (usr.getUserType().equals("4")
						&& usr.getCompany().getId().equals(current.getCompany().getId()) && usr.getOffice().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
				}
			}
			//resultList.add(current);
		} else {
			Set<String> offices = new HashSet<String>();
			for (User usr : list) {
				if (usr.getUserType().equals("3")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
					offices.add(usr.getOffice().getId());
				}
			}
			offices.add(current.getOffice().getId());
			for (User usr : list) {
				if (usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())) {
					resultList.add(usr);
				}
			}
			//resultList.add(current);
		}
		for (User temuser : resultList) {
			temuser.setRemarks(User.DEL_FLAG_NORMAL.equals(temuser.getDelFlag()) ? "正常" : "审核中");
		}
		return resultList;
	}
	public List<User> getSubListForUserForCheck(User current){
		User user = new User();
		user.setDelFlag(null);
		List<User> list = systemService.findList(user);
		Role role = current.getRole();
		List<User> resultList = new ArrayList<User>();
		if (current.getUserType().equals("1")) {
			for (User usr : list) {
				if (!usr.getUserType().equals("1")) {
					resultList.add(usr);
				}
			}
		} else if (current.getUserType().equals("4")) {
			//resultList.add(current);
		} else if (current.getUserType().equals("3")) {
			for (User usr : list) {
				if (usr.getUserType().equals("4")
						&& usr.getCompany().getId().equals(current.getCompany().getId()) && usr.getOffice().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
				}
			}
			//resultList.add(current);
		} else {
			Set<String> offices = new HashSet<String>();
			for (User usr : list) {
				if (usr.getUserType().equals("3")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
					offices.add(usr.getOffice().getId());
				}
			}
			offices.add(current.getOffice().getId());
			for (User usr : list) {
				if (usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())) {
					resultList.add(usr);
				}
			}
			//resultList.add(current);
		}
		for (User temuser : resultList) {
			temuser.setRemarks(User.DEL_FLAG_NORMAL.equals(temuser.getDelFlag()) ? "正常" : "审核中");
		}
		return resultList;
	}
}
